package com.htfyun.serialport.utils;

import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.provider.Settings;
import android.util.Log;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.RandomAccessFile;
import java.io.Writer;
import java.net.Inet4Address;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.List;
import java.util.Locale;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * Created by sst on 15/11/17.
 */
public class UsefulUtil {

    public static String toHexString(byte[] b) {
        if (b == null) {
            return "null";
        }
        if (b.length == 0) {
            return "[]";
        }
        StringBuilder sb = new StringBuilder();
        sb.append('[');
        for (int i = 0; i < b.length; i++) {
            String hex = Integer.toHexString(b[i] & 0xff);
            if (hex.length() == 1) {
                hex = '0' + hex;
            }
            sb.append(hex.toUpperCase());
            if (i < b.length - 1) {
                sb.append(", ");
            }
            if(i != 0 && i%64 == 0) {
                sb.append("\n");
            }

        }
        sb.append(']');
        return sb.toString();
    }

    //http://www.android-study.net/listxx.aspx?id=418
    public static boolean isNumeric(String str) {

//        Pattern pattern = Pattern.compile("[0-9]*");
        Pattern pattern = Pattern.compile("-?[0-9]*");

        Matcher isNum = pattern.matcher(str);

        if (!isNum.matches()) {

            return false;

        }

        return true;

    }


    public static String toHexString(byte[] b, int len) {
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < b.length && i < len; i++) {
            String hex = Integer.toHexString(b[i] & 0xff);
            if (hex.length() == 1) {
                hex = '0' + hex;
            }
            sb.append(hex.toUpperCase() + " ");
            if(i != 0 && i%64 == 0) {
                sb.append("\n");
            }

        }

        return sb.toString();
    }

    public synchronized static void writeStringToFile(String filePath, String content) {
        File file = new File(filePath);
        Writer writer = null;

        try {
            writer = new OutputStreamWriter(new FileOutputStream(file));
            writer.write(content);
            writer.flush();

        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }finally {
            if (writer != null) {
                try {
                    writer.close();
                } catch (Exception e1) {
                    e1.printStackTrace();
                }
            }
        }
    }

    /**
     * 以行为单位读取文件，常用于读面向行的格式化文件
     *
     * @param fileName
     *            文件名
     */
    public synchronized static List<String> readFileContent(String fileName) {
        File file = new File(fileName);
        BufferedReader reader = null;
        List<String> stringList = new ArrayList<String>();
        try {
            reader = new BufferedReader(new FileReader(file));
            String tempString = null;
            while ((tempString = reader.readLine()) != null) {
                stringList.add(tempString.replace(" ", "").replaceAll("\r|\n*", ""));
            }
            reader.close();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (reader != null) {
                try {
                    reader.close();
                } catch (IOException e1) {
                }
            }
        }

        return stringList;
    }

    public synchronized static String readFileByLines(String filePath) {
        File file = new File(filePath);
        BufferedReader reader = null;
        StringBuilder stringBuilder = new StringBuilder("");

        try {
            reader = new BufferedReader(new FileReader(file));
            String tempString = null;
            int line = 1;
            while ((tempString = reader.readLine()) != null) {
//                Log.e(TAG, "line " + line + ": " + tempString);
                line++;
                stringBuilder.append(tempString.replace(" ", "").replaceAll("\r|\n*", ""));
            }
            reader.close();
//            Log.e(TAG, "stringBuilder " + stringBuilder.toString() );

        } catch (IOException e) {

            e.printStackTrace();

        } finally {
            if (reader != null) {
                try {
                    reader.close();
                } catch (IOException e1) {
                }
            }
        }

        return stringBuilder.toString();
    }

    /**
     * 追加文件：使用FileWriter
     *
     * @param fileName
     * @param content
     */
    public static void writeAppendFile(String fileName, String content) {

        File file = new File(fileName);
        if (!file.exists()) {
            try {
                if (!file.getParentFile().exists()) {
                    boolean ret = file.getParentFile().mkdirs();
                }
                file.createNewFile();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        try {

            // 打开一个写文件器，构造函数中的第二个参数true表示以追加形式写文件
            FileWriter writer = new FileWriter(fileName, true);
            writer.write(content);
            writer.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 追加文件：使用RandomAccessFile
     *
     * @param fileName
     *            文件名
     *
     */
    public static void writeAppendFile(String fileName, byte[] buffer, int byteOffset, int byteCount) {
        try {
            // 打开一个随机访问文件流，按读写方式
            RandomAccessFile randomFile = new RandomAccessFile(fileName, "rw");
            // 文件长度，字节数
            long fileLength = randomFile.length();
            // 将写文件指针移到文件尾。
            randomFile.seek(fileLength);
            randomFile.write(buffer, byteOffset, byteCount);
            randomFile.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


    /**
     * //第一种：普遍使用，二次取值
     System.out.println("通过Map.keySet遍历key和value：");
     for (String key : map.keySet()) {
     System.out.println("key= "+ key + " and value= " + map.get(key));
     }

     //第二种
     System.out.println("通过Map.entrySet使用iterator遍历key和value：");
     Iterator<Map.Entry<String, String>> it = map.entrySet().iterator();
     while (it.hasNext()) {
     Map.Entry<String, String> entry = it.next();
     System.out.println("key= " + entry.getKey() + " and value= " + entry.getValue());
     }

     <span style="color:#FF0000;">  //第三种：推荐，尤其是容量大时</span>
     System.out.println("通过Map.entrySet遍历key和value");
     for (Map.Entry<String, String> entry : map.entrySet()) {
     System.out.println("key= " + entry.getKey() + " and value= " + entry.getValue());
     }

     //第四种
     System.out.println("通过Map.values()遍历所有的value，但不能遍历key");
     for (String v : map.values()) {
     System.out.println("value= " + v);
     }
     */
}
